package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import sun.util.resources.cldr.st.CurrencyNames_st_LS;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
@Slf4j
//@Component
public class LoginFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front//**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){  //匹配成功
                filterChain.doFilter(request,response);
                return;
            }
        }

        HttpSession session = request.getSession();
        Employee loginEmployee = (Employee) session.getAttribute("loginEmployee");

        User user = (User) request.getSession().getAttribute("user");

        if (loginEmployee != null || user != null){  //
            //登录成功,向ThreadLocal存入当前用户id
            if(loginEmployee != null){
                Long id = loginEmployee.getId();
                UserHolder.setUserId(id);
            }
            if(user != null){
                UserHolder.setUserId(user.getId());
            }

            filterChain.doFilter(request,response);//放行

            //回来的代码,需要释放ThreadLocal中存储的用户id,避免内存溢出
            UserHolder.release();
        }else { //未登录
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }
    }
}
